// pages/my/my.js
var app = getApp()
Page({
  data: {
    buyType:'',
    goodsList:[],
    role:'',
    goodsPriceShow:true,
    goodsAddShow:true,
    goodsInfoShow:true,
    // coupon:'50',
    settlementPrice:'',
    applyType:0, //扳马0，其他1,付款2
    transportTypeList:['卖家配送','第三方物流','自提'],
    orderId:'',
    fee:'提交购货申请后由卖家填写',
    isCompany:true,
    isMask:false,
    balance:0,
    payType:0 //0微信支付1钱包支付2线下支付
  },
  onLoad: function (options) {
    app.getMemInfo().then(res=>{
      // this.getAddress(res.data.agentId)
      this.setData({
        agentId:res.data.agentId,
        role:res.data.role
      })
      this.getBalance(res.data.agentId)
    })
    // let data = options.orderId.split(',')
    // data.forEach(item=>{
    //   if (item!='') {
    //     this.getOrderDetail(item)
    //   }
    // })
    // this.getOrderDetail(options.orderId)

    this.getOrderDetail(options.orderId)
    this.setData({
      buyType:options.type, //0批发1拼单
      orderId:options.orderId
    })
    let type = options.applyType
    if (type==0) {
      this.setData({
        fee:'￥0.01',
        applyType:type
      })
    }else{
      this.setData({
        fee:'提交购货申请后由卖家填写',
        applyType:type
      })
    }
  },
  getOrderDetail(orderId){
    var that = this
    var data = {
      orderId
    }
    console.log(data)
    app.request('wx_app/agent_order/queryOrderInfoById',data,'GET').then(res=>{
      console.log(res)
      let goodsInfo = []
      let goodsList = this.data.goodsList
      res.data.orderDetails.forEach(item=>{
        goodsInfo.push({
          name:item.name,
          url:item.pic,
          price:item.price==0?"线下商议":item.price,
          type:item.versionValues,
          num:item.amount,
          companyName:res.data.productTag,
          color:res.data.tagColor,
          faceValue:item.faceValue,
          stockSkuId:item.stockSkuId
        })
      })
      goodsList.push({
        orderId:orderId,
        labor_cost:res.data.labor_cost?res.data.labor_cost:0,
        order_no:res.data.orderNo,
        order_time:res.data.createTime,
        product_price:res.data.productPrice,
        order_price:res.data.orderPrice,
        totalPrice:Math.floor((res.data.orderPrice+0.01) * 100) / 100,
        status:res.data.orderState,
        transportType:'卖家配送',
        goodsInfo:goodsInfo,
        address:res.data.address,
        agentAddressId:res.data.addressId,
        name:res.data.contactName,
        phone:res.data.contactPhone,
        companyName:res.data.companyName,
        color:res.data.tagColor,
        logo:res.data.logoUrl,
        note:''
      })
      console.log(goodsList)
      that.setData({
        goodsList
      })
      this.data.goodsList[0].goodsInfo.forEach(item=>{
        if (item.price==='线下商议') {
          this.setData({
            ['goodsList[0].order_price']:0,
            applyType:1,
            fee:'提交购货申请后由卖家填写',
          })
        }
      })
    })
  },
  saveNote(e){
    let i = e.currentTarget.dataset.i
    this.setData({
      ['goodsList['+i+'].note']:e.detail.value
    })
  },
  bindApplyOther(){
    let orderInfos = []
    this.data.goodsList.forEach(item=>{
      orderInfos.push({
        orderId:item.orderId,
        logisticsType:item.transportType,
        note:item.note,
      })
    })
    let data = {
      orderInfos:JSON.stringify(orderInfos),
      agentAddressId:this.data.goodsList[0].agentAddressId,
      payableOrNot:0 //联系厂商付款
    }
    console.log(data)
    app.request('wx_app/agent_order/apply_save',data,'GET').then(res=>{
      console.log(res)
      if (res.code==1) {
        wx.showToast({
          icon:'success',
          title:'申请成功'
        })
        setTimeout(function(){
          wx.switchTab({
            url:'../../my/my'
          })
        },1500)
      }else{
        app.errorMsg(res.message)
      }
    })
  },
  bindApply(){
    if(this.data.goodsList[0].agentAddressId!=null){      
      let orderInfos = []
      this.data.goodsList.forEach(item=>{
        orderInfos.push({
          orderId:item.orderId,
          logisticsType:item.transportType,
          note:item.note
        })
      })
      let data = {
        orderInfos:JSON.stringify(orderInfos),
        agentAddressId:this.data.goodsList[0].agentAddressId,
        payableOrNot:1//等待自己付款
      }
      console.log(data)
      app.request('wx_app/agent_order/apply_save',data,'GET').then(res=>{
        console.log(res)
        if (res.code==1) {
          this.setData({
            applyType:2,
          })
        }else{
          app.errorMsg(res.message)
        }
      })
      this.setData({
        isMask:true
      })
    }else{
      app.errorMsg('请添加收货地址')
    }
  },
  bindPay(){
    this.setData({
      isMask:true
    })
  },
  cancle(){
    this.setData({
      isMask:false
    })
  },
  confirm(){
    wx.showLoading({
      title:'正在支付'
    })
    let that = this
    this.setData({
      isMask:false
    })
    if (this.data.payType==0) {//微信支付
      let data = {
        orderId:this.data.goodsList[0].orderId
      }
      app.request('wx_app/agent_order/payment',data,'GET').then(res=>{
        console.log(res)
        if (res.code==1) {   
          let date = Date.parse(new Date())   
          wx.requestPayment({
            timeStamp: res.data.timeStamp,
            nonceStr: res.data.nonceStr,
            package: res.data.package,
            signType: 'MD5',
            paySign: res.data.sign,
            success(res){
              console.log(res)
              wx.hideLoading()
              wx.showToast({
                title:'支付成功'
              })
              if (that.data.buyType==0) {
                setTimeout(function(){
                  wx.switchTab({
                    url:'../../my/my'
                  })
                },1000)
              }else{
                setTimeout(function(){
                  wx.redirectTo({
                    url:'./together/together?orderId='+that.data.orderId+'&stockSkuId='+that.data.goodsList[0].goodsInfo[0].stockSkuId
                  })
                },1000)
              }
            },
            fail(){
              wx.hideLoading()
            },
            complete(){
              wx.hideLoading()
              if (that.data.buyType==0) {
                setTimeout(function(){
                  wx.switchTab({
                    url:'../../my/my'
                  })
                },1000)
              }else{
                setTimeout(function(){
                  wx.redirectTo({
                    url:'./together/together?orderId='+that.data.orderId+'&stockSkuId='+that.data.goodsList[0].goodsInfo[0].stockSkuId
                  })
                },1000)
              }
            }
          })
        }else{
          wx.hideLoading()
          app.errorMsg('支付失败')
        }
      })
    }else if (this.data.payType==1) {//钱包支付
      if (this.data.balance<this.data.goodsList[0].totalPrice) {
        app.errorMsg('您的余额不足')
      }else{      
        let data = {
          orderId:this.data.goodsList[0].orderId
        }
        app.request('wx_app/agent_order/walletPayment',data,'GET').then(res=>{
          console.log(res)
          if (res.code==1) {
            wx.hideLoading()
            wx.showToast({
              title:'支付成功'
            })
            if (that.data.buyType==0) {
              console.log(that.data.buyType)
              setTimeout(function(){
                wx.switchTab({
                  url:'../../my/my'
                })
              },1000)
            }else{
              console.log(that.data.buyType)
              setTimeout(function(){
                wx.redirectTo({
                  url:'./together/together?orderId='+that.data.orderId+'&stockSkuId='+that.data.goodsList[0].goodsInfo[0].stockSkuId
                })
              },1000)
            }
          }else{  
            wx.hideLoading()
            app.errorMsg(res.message)
          }
        })
      }
    }else{//线下支付
      wx.showToast({
        icon:'success',
        title:'申请成功'
      })
      setTimeout(function(){
        wx.switchTab({
          url:'../../my/my'
        })
      },1500)
    }
  },
  bindChoose(e){
    let type = e.currentTarget.dataset.type //1微信支付2钱包支付3线下支付
    this.setData({
      payType:type
    })
  },
  collectAddress(){
    wx.navigateTo({
      url:'../address/address?type=1'
    })
  },
  choseTransType(e){
    console.log(e.currentTarget.dataset.i)
    let i = e.currentTarget.dataset.i
    this.setData({
      ['goodsList['+i+'].transportType']:this.data.transportTypeList[e.detail.value]
    })
  },
  getAddress(agentId){
    let data = {
      agentId
    }
    app.request('wx_app/agent/address/list',data,'GET').then(res=>{
      console.log(res.data[0])
      this.setData({
        address:res.data[0].address,
        name:res.data[0].contactName,
        phone:res.data[0].mobilePhone,
        addressId:res.data[0].id
      })
    })
  },
  getBalance(agentId){
    let data = {
      agentId
    }
    app.request('wx_app/agent/account/accountBalance',data,'GET').then(res=>{
      console.log(res)
      if (res.code==1) {
        this.setData({
          balance:res.data==null?0:res.data
        })
      }else{
        app.errorMsg(res.message)
      }
    })
  },
  //选择收货地址
  selectAddress(){
    wx.navigateTo({
      url:'selectAddress'
    })
  },
  //数量及价格控制
  add(e){
    let num = e.currentTarget.dataset.num
    num++
    this.setData({
      ['goodsList[0].goodsInfo[0].num']:num
    })
    this.priceControl(num)
  },
  sub(e){
    let num = e.currentTarget.dataset.num
    num--
    if (num>0) {    
      this.setData({
        ['goodsList[0].goodsInfo[0].num']:num
      })
      this.priceControl(num)
    }
  },
  priceControl(num){
    let price = this.data.goodsList[0].goodsInfo[0].price
    this.setData({
      ['goodsList[0].order_price']:parseInt(num)*price,
      ['goodsList[0].totalPrice']:parseInt(num)*price+0.01
    })
  },
  //申请拼单
  togetherApply(){
    if(this.data.goodsList[0].agentAddressId!=null){
      let data = {
        orderId:this.data.orderId,
        note:this.data.goodsList[0].note,
        count:this.data.goodsList[0].goodsInfo[0].num,
        stockSkuId:this.data.goodsList[0].goodsInfo[0].stockSkuId,
        logisticsType:this.data.goodsList[0].transportType,
        agentAddressId:this.data.goodsList[0].agentAddressId
      }
      console.log(data)
      app.request('wx_app/together/apply_save',data,'GET').then(res=>{
        console.log(res)
        if (res.code==1) {
          this.setData({
            applyType:2,
            isMask:true
          })
        }else{
          app.errorMsg(res.message)
        }
      })
    }else{
      app.errorMsg('请添加收货地址')
    }
  }
})